from core.query.query_processor import QueryProcessor
from config.config import (
    API_ENDPOINT, LOCAL_MODEL_NAME, 
    REMOTE_API_KEY, REMOTE_API_ENDPOINT, REMOTE_MODEL_NAME,
    FILE_PATH, EXPLANATION_FILE
)
from core.memory.session_manager import SessionManager
from core.utils.logging_handler import LoggingHandler
from core.data.markdown_converter import MarkdownConverter
import pandas as pd
import gradio as gr

# 初始化日志记录器
logger = LoggingHandler().get_logger()

def process_query(user_input, history, use_remote=True):
    logger.info("应用程序启动")
    # 初始化会话管理器
    session_manager = SessionManager()    
    try:  
        # 获取用户输入
        logger.info(f"用户输入: {user_input}")
        
        if user_input.lower() == 'exit':
            logger.info("用户终止对话")
            print("结束对话。")
            return "对话已结束。"

        data_file = FILE_PATH
        explanation_file = EXPLANATION_FILE

        if use_remote:
            # 使用远程模型
            api_key = REMOTE_API_KEY
            base_url = REMOTE_API_ENDPOINT
            model_name = REMOTE_MODEL_NAME
        else:
            # 使用本地模型
            api_key = None
            base_url = API_ENDPOINT
            model_name = LOCAL_MODEL_NAME

        # 初始化 QueryProcessor 并传递对话历史
        processor = QueryProcessor(
            user_input=user_input, 
            file_path=data_file, 
            api_key=api_key, 
            base_url=base_url, 
            local_model_name=model_name, 
            remote_model_name=REMOTE_MODEL_NAME, 
            explanation_file=explanation_file, 
            use_remote=use_remote
        )
        
        # 处理用户输入
        processor.process()

        # 判断是否为闲聊应答，如果是闲聊应答则直接返回结果
        if processor.result_txt and "闲聊应答" in processor.result_txt:
            session_manager.add_to_history(user_input, processor.result_txt)
            session_manager.save_memory()
            return processor.result_txt
        
        # 获取结果并添加到会话历史
        if processor.result_presenter:
            logger.info(f"处理后的结果类型: {type(processor.result_presenter.result)}")
            logger.info(f"处理后的总结类型: {type(processor.result_summary)}")
            
            result = "# 查询结果：\n"
            result += MarkdownConverter.convert_to_markdown(processor.result_presenter.result)
            result += "\n---\n"
            result += "# 总结结果：\n"
            result += processor.result_summary
        else:
            result = processor.result_txt

        # 保存到会话历史并返回结果
        session_manager.add_to_history(user_input, result)
        session_manager.save_memory()
        return result

    except Exception as e:
        logger.error(f"发生异常: {e}", exc_info=True)
        return f"处理过程中发生异常: {e}"

